import { PinCode } from "../pin-code"
import { IStorage } from "../../bcat/storage/i-storage"
import { Storage } from "../../bcat/storage/storage"

export class PinCodeStorage {
  static KeyPinCode: string = "KeyPinCode";
  static from(storage: IStorage): PinCodeStorage {
    return new PinCodeStorage(storage);
  }
  
  storage: IStorage;
  constructor(storage: IStorage) {
    this.storage = storage;
  }

  load(): PinCode | undefined {
    const s = this.storage.loadString(PinCodeStorage.KeyPinCode);
    return s !== undefined ? PinCode.from(s) : undefined;
  }

  //true -> insert 
  //false -> replace
  //undefined -> failed
  save(pinCode: PinCode): boolean | undefined {
    if(pinCode !== undefined){
      return this.storage.saveString(PinCodeStorage.KeyPinCode, pinCode.value);
    }
    return undefined;
  }

  delete(): string | undefined {
    const r = this.storage.delete(PinCodeStorage.KeyPinCode);
    return (typeof r === 'string') ? r : undefined;
  }
  exists(): boolean {
    return undefined !== this.storage.loadString(PinCodeStorage.KeyPinCode);
  }
}


export function test() {
  const pcs = PinCodeStorage.from(Storage.default());
  const pinCode = pcs.load();
  console.log(pinCode === undefined);
  console.log(pcs.save(pinCode) === undefined);

  
  const psd = "123456";
  console.log(pcs.save(PinCode.from(psd)) == true);
  console.log(pcs.load().value == psd);
  
  const psd_1 = "234567";
  console.log(pcs.save(PinCode.from(psd_1)) == true);
  console.log(pcs.load().value == psd_1);

  pcs.delete();
}
